package org.university.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.university.common.ApiResponse;
import org.university.entity.Major;
import org.university.exception.ResourceNotFoundException;
import org.university.service.MajorService;

@CrossOrigin
@RestController
@RequestMapping("/majors")
public class MajorController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MajorController.class);
    private final MajorService majorService;

    public MajorController(MajorService majorService) {
        this.majorService = majorService;
    }

    /**
     * 获取专业信息分页
     *
     * @param page 页码
     * @param size 页面大小
     * @return 信息分页
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<Major>>> getMajor(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        LOGGER.info("查询专业：页码={}, 每页大小={}", page, size);
        Page<Major> majors = majorService.findAll(PageRequest.of(page, size));
        return ApiResponse.success(majors);
    }

    /**
     * 根据ID查找专业
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Major>> getMajorById(@PathVariable Integer id) {
        LOGGER.info("查询专业ID: {}", id);
        return majorService.findById(id)
                .map(ApiResponse::success)
                .orElseThrow(() -> new ResourceNotFoundException("未找到id为：" + id + " 的专业"));
    }

    /**
     * 创建专业
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Major>> createMajor(@RequestBody Major major) {
        LOGGER.info("创建专业ID: {}", major.getMajorId());
        Major newMajor = majorService.save(major);
        return ApiResponse.created(newMajor);
    }

    /**
     * 更新专业信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Major>> updateMajor(
            @PathVariable Integer id,
            @RequestBody Major major) {

        LOGGER.info("更新专业ID: {}", id);
        if (majorService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, new String("未找到id为：" + id + " 的专业"));
        }
        major.setMajorId(id);
        Major updatedMajor = majorService.save(major);
        return ApiResponse.success(updatedMajor);
    }

    /**
     * 删除专业
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMajor(@PathVariable Integer id) {
        LOGGER.info("删除专业ID: {}", id);
        if (majorService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, new String("未找到id为：" + id + " 的专业"));
        }
        majorService.deleteById(id);
        return ResponseEntity.ok().build();
    }
}
